package com.xb.chain.utils;

import com.mysql.cj.jdbc.ConnectionGroupManager;
import com.xb.chain.constant.InfoConstant;
import com.xb.chain.netty.server.NodeServerStart;

import java.sql.*;

/**
 * @author xiaobin
 * @date 2020/2/22 19:43
 * @desc
 */
public class JdbcUtil {

    public static Connection connection;
    public static Object object = new Object();
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("mysql驱动加载失败");
        }
    }

    public static Connection getConnection() {
        try {
            if (connection == null) {
                synchronized (object) {
                    if (connection == null) {
                        JdbcUtil.connection = DriverManager.getConnection(NodeServerStart.blockChainProperties.getDbUrl(),NodeServerStart.blockChainProperties.getDbUsername(),NodeServerStart.blockChainProperties.getDbPassword());
                    }
                }
            }
        } catch (SQLException e) {
            System.err.println("mysql连接信息错误");
        }
        return JdbcUtil.connection;
    }


    public static void closeConnection(Statement statement, ResultSet resultSet) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeConnection(Statement statement) {
        closeConnection(statement, null);
    }

    public static void closeConnection(ResultSet resultSet) {
        closeConnection(null, resultSet);
    }

}
